package Network

import (
	"logs"
	"net/http"
)

const (
	noticeOffline    = 251
	noticeLogin      = 252
	noticeForceQuit  = 253
	noticeLoginAgain = 254
)
const (
	mOffline    = "OFFLINE"
	mLogin      = "LOGIN SUCCESS"
	mForceQuit  = "FORCE QUIT"
	mLoginAgain = "TWO CLIENTS LOGIN"
)

type LoginInfo struct {
	UserName string `json:"UserName"`
	IconURL  string `json:"IconURL"`
	UserID   string `json:"UserID"`
}

// --------------------------------------------- 连接创建、消息创建部分
// wsLogin 初始化WebSocket连接，
// 		   每个客户端都需要连接/wsLogin接口以建立WebSocket连接
// ws://ficow.cn:8001/wsLogin?account=15521133823&password=123456
func wsLogin(w http.ResponseWriter, r *http.Request) {

	var errCode = Success
	var errMsg = ""

	upgrader.CheckOrigin = func(r *http.Request) bool { //关闭Origin检查
		return true
	}
	ws, err := upgrader.Upgrade(w, r, nil)

	defer func() {
		if ws != nil {
			err = ws.WriteJSON(ServerResponse{"/wsLogin", errCode, errMsg, nil})
			if err != nil {
				logs.Print("ws.WriteJSON 发生了错误：", err.Error())
			}
			ws.Close()
		} else if err != nil {
			logs.Print("*** WebSocket CONNECT FAILED!\nerr:", err.Error())
			writeHTTPResult(w, errBadWebsocket, mBadWebsocket+err.Error(), nil)
		}
	}()

	account := r.FormValue("account")
	password := r.FormValue("password")
	logs.Print("account:", account, "password:", password)

	ok := false
	if ok, errCode, errMsg = isArgsEmptyInHTTP(account, password); ok {
		return
	}
	if ok, errCode, errMsg = isValidAccountInHTTP(account); !ok {
		return
	}
	if ok, errCode, errMsg = isValidPwdInHTTP(password); !ok {
		return
	}

	var loginInfo LoginInfo
	errCode, errMsg, loginInfo = checkLogin(account, password)
	if errCode != Success {
		logs.Print(account, " login FAILED!")
		return
	}

	clientID := loginInfo.UserID
	loginResult := map[string]string{
		"UserID":   loginInfo.UserID,
		"IconURL":  loginInfo.IconURL,
		"UserName": loginInfo.UserName,
	}
	if !addClient(clientID, ws) {
		writeResponseToClient(clientID, &ServerResponse{
			Method:  "/wsLogin",
			Code:    noticeLoginAgain,
			Message: mLoginAgain,
			Result:  loginResult,
		})
	} else {
		writeResponseToClient(clientID, &ServerResponse{
			Method:  "/wsLogin",
			Code:    noticeLogin,
			Message: mLogin,
			Result:  loginResult,
		})
		logs.Print(clientID, mLogin)
	}

	// 登录便获取会话列表信息
	writeResponseToClient(clientID, sessionList(clientID, nil))

	processClientMsg(clientID, ws)
}
